package daily.nov;

import java.util.ArrayList;

public class lc1437 {
    /*
    采用arraylist来做非常简单，但是要不断查询。arraylist不适合频繁查询，所以时间上效率比较低。可以考虑用别的方法优化。
     */

    public boolean kLengthApart(int[] nums, int k) {
        ArrayList<Integer> list = new ArrayList<>();//存储数组中所有1的位置
        for (int i=0; i<nums.length; i++) {
            if (nums[i] == 1){
                list.add(i);//在list中存储1的索引位置
            }
        }

        for (int i=1; i<list.size(); i++) {
            int index1 = list.get(i);
            int index2 = list.get(i-1);
            int diff = Math.abs(index1-index2);
            if (diff<(k+1)){//注意，diff为2时，实际上两个1之间的间隔是1。这里将k+1来抵消这个误差
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        lc1437 lc1437 = new lc1437();
        int[] nums1 = {1,0,0,0,1,0,0,1};
        int k1 = 2;
        System.out.println(lc1437.kLengthApart(nums1,k1));

        int[] nums2 = {1,0,0,1,0,1};
        int k2 = 2;
        System.out.println(lc1437.kLengthApart(nums2,k2));
    }
}
